//
//  ViewController.swift
//  likeQQ
//
//  Created by 邹佳林 on 16/7/25.
//  Copyright © 2016年 邹佳林. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    var homeViewController: HomeViewController!
    
    //侧滑菜单视图来源
    var leftViewController: LeftViewController!
    
    //首页navigation
    var homeNavigationController: UINavigationController!
    
    //tabBar
    var mainTabBarController: MainTabBarController!
    
    //主界面点击手势
    var tapGesture: UIGestureRecognizer!
    
    //构造主视图 实现uinavigationcontroller和homeview一起缩放
    var mainView: UIView!
    
    //侧滑所需参数
    var distance: CGFloat = 0
    
    let FullDistance: CGFloat = 0.78
    let Proportion: CGFloat = 0.77
    var centerOfLeftViewAtBeginning: CGPoint!
    var proportionOfLeftView: CGFloat = 1
    var distanceOfLeftView: CGFloat = 50
    //侧滑菜单半透明罩层
    var blackCover: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //给主视图设置背景
        let imageView = UIImageView(image: UIImage(named: "back"))
        imageView.frame = UIScreen.mainScreen().bounds
        self.view.addSubview(imageView)
        
        /*
        //通过storyboard取出HomeViewController的View，放在背景视图的上面
        homeViewController = UIStoryboard(name: "Main",bundle: nil).instantiateViewControllerWithIdentifier("HomeViewController") as! HomeViewController
        self.view.addSubview(homeViewController.view)
        */
 
 
        
        //通过storyboard取出左侧侧滑菜单视图
        leftViewController = UIStoryboard(name: "Main",bundle: nil).instantiateViewControllerWithIdentifier("LeftViewController") as! LeftViewController
        
        
        //适配屏幕大小
        if Common.screeWidth > 320
        {
            proportionOfLeftView = Common.screeWidth / 320
            distanceOfLeftView += (Common.screeWidth - 320) * FullDistance / 2
        }
        leftViewController.view.center = CGPointMake(leftViewController.view.center.x - 50, leftViewController.view.center.y)
        leftViewController.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.8, 0.8)
 
        
        //动画参数初始化
        centerOfLeftViewAtBeginning = leftViewController.view.center
        
        //把侧滑菜单视图加入根容器
        self.view.addSubview(leftViewController.view)
        
        //实现侧滑菜单黑色罩层，实现视差特效
        blackCover = UIView(frame: CGRectOffset(self.view.frame,0,0))
        blackCover.backgroundColor = UIColor.blackColor()
        self.view.addSubview(blackCover)
        
        //初始化主视图，包含tabbar，navigationbar
        mainView = UIView(frame: self.view.frame)
        
        //初始化tabbar
        let nibContents = NSBundle.mainBundle().loadNibNamed("MainTabBarController", owner: nil, options: nil)
        mainTabBarController = nibContents.first as! MainTabBarController
        
        //取出tabbar的视图加入主视图
        let tabBarView = mainTabBarController.view
        mainView.addSubview(tabBarView)
        
        //从storyboard中取出首页的navigation
        homeNavigationController = UIStoryboard(name: "Main",bundle: nil).instantiateViewControllerWithIdentifier("HomeNavigationController") as! UINavigationController
        
        //storyBoard中的navigation会自动初始化它的rootview，即homeview
        //我们将其取出，赋值给容器viewcontroller的成员变量homeviewcontroller
        homeViewController = homeNavigationController.viewControllers.first as! HomeViewController
        
        //分别将navigation bar 和 homeview 的视图加入 tabbar controller的视图
        tabBarView.addSubview(homeViewController.navigationController!.view)
        tabBarView.addSubview(homeViewController.view)
        
        //将tabbar视图提到最表层
        tabBarView.bringSubviewToFront(mainTabBarController.tabBar)
        
        //将主视图加入容器
        self.view.addSubview(mainView)
        
        //分别指定navigation bar 左右两侧的事件
        homeViewController.navigationItem.leftBarButtonItem?.action = Selector("showLeft")
        homeViewController.navigationItem.rightBarButtonItem?.action = Selector("showRight")
        
        //给主视图绑定UIpangesture
        let panGesture = homeViewController.panGesture
        panGesture.addTarget(self, action: Selector("pan:"))
        mainView.addGestureRecognizer(panGesture)
        
        //生成单击收起菜单手势
        tapGesture = UIPanGestureRecognizer(target: self,action: "showHome")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //响应UIPanGestureRecognizer事件
    func pan(recognizer: UIPanGestureRecognizer)
    {
        let x = recognizer.translationInView(self.view).x
        let tureDistance = distance + x  //实时距离
        let trueProportion = tureDistance / (Common.screeWidth * FullDistance)
        
        //如果 UIPanGestureRecognizer 结束，则激活自动停靠
        if recognizer.state == UIGestureRecognizerState.Ended
        {
            if tureDistance > Common.screeWidth * (Proportion / 3)
            {
                showLeft()
            }
            else if tureDistance < Common.screeWidth * -(Proportion / 3)
            {
                showRight()
            }
            else
            {
                showHome()
            }
            
            return
        }
        //计算缩放比例
        var proportion: CGFloat = recognizer.view!.frame.origin.x >= 0 ? -1 : 1
        proportion *= tureDistance / Common.screeWidth
        proportion *= 1 - Proportion
        proportion /= 0.6
        proportion += 1
        if proportion <= Proportion
        {
            //若比例达到最小，则不再继续动画
            return
        }
        //执行视差特效
        blackCover.alpha = (proportion - Proportion) / (1 - Proportion)
        
        //执行平移和缩放画面
        recognizer.view!.center = CGPointMake(self.view.center.x + tureDistance, self.view.center.y)
        recognizer.view!.transform = CGAffineTransformScale(CGAffineTransformIdentity, proportion, proportion)
        
        //执行左视图动画
        let pro = 0.8 + (proportionOfLeftView - 0.8) * trueProportion
        leftViewController.view.center = CGPointMake(centerOfLeftViewAtBeginning.x + distanceOfLeftView * trueProportion, centerOfLeftViewAtBeginning.y - (proportionOfLeftView - 1) * leftViewController.view.frame.height * trueProportion / 2)
        leftViewController.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, pro, pro)
    }
    
    //封装三个方法以便后期调用
    
    //展示左视图
    func showLeft()
    {
        //给首页加入 点击自动关闭侧滑菜单功能
        mainView.addGestureRecognizer(tapGesture)
        //计算距离
        distance = self.view.center.x * (FullDistance * 2  + Proportion - 1)
        doTheAnimate(self.Proportion,showWhat: "left")
        homeNavigationController.popViewControllerAnimated(true)
    }
    //展示右视图
    func showRight()
    {
        //给首页加入 点击自动关闭侧滑菜单功能
        mainView.addGestureRecognizer(tapGesture)
        //计算距离
        distance = self.view.center.x * -(FullDistance * 2 + Proportion - 1)
        doTheAnimate(self.Proportion,showWhat: "right")
    }
    //展示主视图
    func showHome()
    {
        //从首页 删除 点击自动关闭侧滑菜单功能
        mainView.removeGestureRecognizer(tapGesture)
        //计算距离
        distance = 0
        doTheAnimate(1,showWhat: "home")
    }
    
    //执行三种视图展示
    func doTheAnimate(proportion: CGFloat,showWhat: String)
    {
        UIView.animateWithDuration(0.3,delay: 0,options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
            //移动首页中心
            self.mainView.center = CGPointMake(self.view.center.x + self.distance, self.view.center.y)
            //缩放首页
            self.mainView.transform = CGAffineTransformScale(CGAffineTransformIdentity, proportion, proportion)
            if showWhat == "left"
            {
                //移动左侧的菜单中心
                self.leftViewController.view.center = CGPointMake(self.centerOfLeftViewAtBeginning.x + self.distanceOfLeftView,self.leftViewController.view.center.y)
                //缩放左侧菜单
                self.leftViewController.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, self.distanceOfLeftView, self.proportionOfLeftView)
            }
            //改变黑色罩层的透明度，实现效果差
            self.blackCover.alpha = showWhat == "home" ? 1 : 0
            
            /*
            //为了掩饰效果，在右侧菜单划出时隐藏左侧菜单
            self.leftViewController.view.alpha = showWhat == "right" ? 1 : 0*/
            
            },completion: nil)
    }
}












